package org.tao.lightningmq.nameserver.handler;

import com.alibaba.fastjson2.JSON;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.tao.lightningmq.common.enums.NameServerEventCode;
import org.tao.lightningmq.common.event.EventBus;
import org.tao.lightningmq.common.event.model.BaseEvent;
import org.tao.lightningmq.common.tcp.TcpMsg;
import org.tao.lightningmq.nameserver.common.CommonCache;
import org.tao.lightningmq.nameserver.event.model.NodeReplicationMsgEvent;

/**
 * @Author lht
 * @date 2025/1/17 - 14:49
 * @description:
 */
@ChannelHandler.Sharable
public class NodeWriteMsgReplicationServerHandler extends SimpleChannelInboundHandler<TcpMsg> {

    private EventBus eventBus;

    public NodeWriteMsgReplicationServerHandler(EventBus eventBus) {
        this.eventBus = eventBus;
        this.eventBus.init();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TcpMsg tcpMsg) throws Exception {
        int code = tcpMsg.getCode();
        byte[] body = tcpMsg.getBody();
        BaseEvent event = null;
        if (NameServerEventCode.NODE_REPLICATION_MSG.getCode() == code) {
            event = JSON.parseObject(body, NodeReplicationMsgEvent.class);
        }
        event.setContext(channelHandlerContext);
        CommonCache.setPreNodeChannel(channelHandlerContext.channel());
        eventBus.publish(event);
    }
}
